package com.gosophia.conferenceManagement.jbpm;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.gosophia.conferenceManagement.ConferenceConfiguration;
import com.gosophia.conferenceManagement.common.entity.ConferenceJobData;
import com.gosophia.conferenceManagement.confPreparation.entity.ConfPreparationJobData;
import com.gosophia.taskManagement.entity.Job;
import com.gosophia.taskManagement.entity.JobData;
import com.gosophia.taskManagement.entity.Mission;
import com.gosophia.taskManagement.service.impl.AbstractNodeActionHandler;
import com.gosophia.userManagement.entity.UserInfo;
import com.gosophia.userManagement.service.UserManagementService;

/**
 * 功能：会议总结起草ActionHandler
 * @author wangxinbing
 * @since  2011-4-8
 *  Copyright (c) 2010 Gosophia corporation All Rights Reserved
 */
@Service("conferenceSummaryStratActionHandler")
@Transactional
public class ConferenceSummaryStratActionHandler extends AbstractNodeActionHandler{

	private static final long serialVersionUID = 1L;
	private final Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    @SuppressWarnings("unchecked")
	private HashMap conferenceConfiguration;
    @Autowired
    private UserManagementService userManagementService;
	@Override
	public List<Job> createNewJobsAfterEnteringNode(Mission mission,
			String nodeName, String operationName, JobData jobData) {
		logger.debug("进入【"+nodeName+"】节点");
	    // 任务开始时间
		Date startDate = new Date();
		String jobDataType = null;
		JobData jobData1 = null;
		if(jobData !=null){
			jobDataType = jobData.getClass().getSimpleName();
		}
		if("ConfPreparationJobData".equalsIgnoreCase(jobDataType)){
			jobData1 =(ConfPreparationJobData)jobData;
		}else{
			jobData1 = (ConferenceJobData)jobData;
		}
//		ConferenceJobData conferenceJobData = (ConferenceJobData)jobData;
		// 任务计划结束时间
		Date scheduleEndDate = mission.getScheduleEndDate();
		NodeConfiguration nodeConfiguration = (NodeConfiguration)conferenceConfiguration.get(nodeName);
		 Assert.notNull(nodeConfiguration);
		 String bsSection=nodeConfiguration.getBsSection();
		List<JobConfiguration> jobConfigurations = nodeConfiguration.getJobConfs();
		 
		 List<Job> jobs = new ArrayList<Job>();
		 for (JobConfiguration jobConf : jobConfigurations) {
		     UserInfo jobSource = new UserInfo();
		    	 
             UserInfo jobUnderTaker = new UserInfo();
              if("ConfPreparationJobData".equalsIgnoreCase(jobDataType)){
            	  jobSource = jobData1.getJob().getOperator();
            	  Object conf_assign = getCurrentContext().getVariable(ConferenceConfiguration.CONFERENCE_APP_ASSIGN);
            	  if(conf_assign !=null){
            		  jobUnderTaker = userManagementService.findUserInfoByUserInfoId((Long)conf_assign);
            	  }else{
                	  jobUnderTaker = mission.getUndertaker(); 
            	  }
              }else{
            	  jobSource= getJobSource(mission,(ConferenceJobData)jobData1);//任务来源
            	  jobUnderTaker= dynamicJobUnderTaker(mission,bsSection,jobConf,(ConferenceJobData)jobData1);//任务承办人
              }

		    
             Job job = createJob(jobConf.getJobType(),//任务类型
		             jobConf.getJobState(),//任务创建后的状态 
		             startDate,//任务开始时间
		                scheduleEndDate, //任务计划结束时间
		                jobUnderTaker, //任务承办人
		                jobSource,//任务来源
		                obtainAfterFinishFlag(nodeConfiguration),
		                jobConf.getDetailURL()
		                         , jobConf.getHandlerURL());
		     jobs.add(job);
		     logger.debug("【"+nodeName+"节点】"+"  actionHandler处理,"+"创建 job jobType：["+ job.getJobType() +"]"
		             +"  job 来自：[id:"+jobSource.getUserInfoId()+",name:"+jobSource.getUserName()
                     +"] job承办人：[id:"+jobUnderTaker.getUserInfoId()+",name:"+jobUnderTaker.getUserName()+"]"
		     );
             }
		return jobs;
	}

	//此方法暂时能够满足业务需求，可以修正使用动态处理类绑定的方法，处理不同情况下的任务承办人分配
	private UserInfo dynamicJobUnderTaker(Mission mission,String bsSection,JobConfiguration jobConf,ConferenceJobData prejobData){
	    //根据节点，如果是审批节点，就是jobData中的下一个审批人，其他节点统统都是大任务的承办人
	    if(jobConf.isGetBackAble()){//取回的任务
            return obtainConferenceAssignUnderTaker(mission,bsSection);
        }else if (prejobData!=null && prejobData.getNextApproval()!=null){
		      return prejobData.getNextApproval();//审批任务的承办人
		  }
	    else 
	         return obtainConferenceAssignUnderTaker(mission,bsSection);
		  }
		 
	//获取会议申请中指定的会议承办人
	private UserInfo obtainConferenceAssignUnderTaker(Mission mission,String bsSection){
	    Object conf_assign = getCurrentContext().getVariable(ConferenceConfiguration.CONFERENCE_APP_ASSIGN);
	    if(conf_assign!=null && !"会议申请环节".equals(bsSection) ){
	        logger.debug("会议申请环节后的承办人："+(conf_assign));
	        return userManagementService.findUserInfoByUserInfoId((Long)conf_assign);
	    }else{
	        return mission.getUndertaker();
	    }
	}
	
	private String obtainAfterFinishFlag(NodeConfiguration nodeConfig ){
		return  nodeConfig.getJobRelation(); 
	}
	//获取任务来源
	private UserInfo getJobSource(Mission mission,ConferenceJobData jobData){
	    if(jobData==null){
	        return  mission.getCreator();
	    }
	    return jobData.getJob().getOperator();
	}
	
	
}
